package com.kabuda.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kabuda.blog.common.FileUpDown;
import com.kabuda.blog.dao.pojo.ArticleTag;
import com.kabuda.blog.dao.pojo.Tag;
import com.kabuda.blog.mapper.ArticleTagMapper;
import com.kabuda.blog.mapper.TagMapper;
import com.kabuda.blog.service.ITagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.List;

/**
 * @author kabuda
 * @create 2023-04-03 21:39
 */
@Service
public class TagServiceImpl extends ServiceImpl<TagMapper, Tag> implements ITagService {

    @Autowired
    private TagMapper tagMapper;

    @Autowired
    private ArticleTagMapper articleTagMapper;

    private final String  folder="Tag";

    @Override
    public void down(String fileName, HttpServletResponse response) {
        FileUpDown.down(fileName,response,folder);
    }

    @Override
    public String up(MultipartFile img) {
        String fileName = FileUpDown.up(img,folder);
        return fileName;
    }

    @Override
    public int ArticleByTagCount(Long tagId) {
        LambdaQueryWrapper<ArticleTag> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ArticleTag::getTagId,tagId);
        Integer count = articleTagMapper.selectCount(wrapper);
        return count;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteRelation(Long id) {
        boolean b = this.removeById(id);
        int delete=0;
        if(b){
            QueryWrapper<ArticleTag> wrapper = new QueryWrapper<>();
            wrapper.eq("tag_id",id);
             delete = articleTagMapper.delete(wrapper);
        }
        if(delete>0){
            return true;
        }else{
            throw new RuntimeException("删除关系失败");
        }
    }

    @Override
    public List<Tag> getTagsByArticleId(long authorId) {
        List<Tag> tags=this.baseMapper.getTagsByAuthorId(authorId);
        return tags;
    }

}
